<?php

namespace App\Http\Controllers\Api;

use App\AgentApply;
use App\AgentList;
use App\Classify;
use App\Course;
use App\CourseCollection;
use App\CourseContent;
use App\CourseCoverImg;
use App\CourseLabel;
use App\CoursePackage;
use App\CoursePackageXCourse;
use App\CourseQuestion;
use App\CourseQuestionAnswerRecord;
use App\CourseQuestionOption;
use App\CourseSignRecord;
use App\CourseStudyLenght;
use App\CourseType;
use App\Files;
use App\Http\Services\AdminManager;
use App\Http\Services\FileManager;
use App\Http\Services\ToolsManager;
use App\Http\Services\UserManager;
use App\Http\Services\Wechat\WechatLogin;
use App\Images;
use App\IntegralDetail;
use App\OrderItem;
use App\Orders;
use App\SystemGroup;
use App\SystemGroupXCourse;
use App\Teacher;
use App\User;
use App\UserCoursePoster;
use App\UserGroup;
use App\UserGroupXUser;
use App\UserInfo;
use Composer\Package\Package;
use Endroid\QrCode\QrCode;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;
use Intervention\Image\Facades\Image;

class CourseController extends Controller
{
    /**
     * 获取课程列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCourseList(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        $userId = $user ? $user->id : 0;
        if($userId){
            $is_payed_id=Orders::whereUserId($user->id)
                ->whereIsPay(1)
                ->whereIsSuccess(1)
                ->pluck('id')->toArray();
            $buy_ids = OrderItem::whereUserId($user->id)->whereIn('order_id',$is_payed_id)->pluck('course_id')->toArray();
        } else {
            $buy_ids=[];
        }
        $page       = $request->input('page',1);
        $limit      = $request->input('limit',10);
        $keyword    = $request->input('keyword');
        $study_type = $request->input('study_type');
        $teacher_id = $request->input('teacher_id');
        $is_featured= $request->input('is_featured');
        $classify_id= $request->input('classify_id');
        $order_by   = $request->input('order_by');
        $isAgentPromotion = $request->input('is_agent_promotion') ?? '';

        $page_info=[
            'page'=>$page,
            'limit'=>$limit
        ];
        $page = $page-1;

        /** @var Course $data */
        $data       = Course::whereStatus(1);
        if (trim($keyword)){
            $teacherIds = Teacher::where('name','like','%'.trim($keyword).'%')->pluck('id')->toArray();
            $data=$data->whereIn('teacher_id',$teacherIds)->orWhere('name','like','%'.trim($keyword).'%');
        }

        if(is_numeric($isAgentPromotion)){
            $data=$data->whereIsAgentPromotion($isAgentPromotion);
        }

        if ($study_type){
            $data=$data->whereStudyType($study_type);
        }

        if (is_numeric($teacher_id)){
            $data=$data->whereTeacherId($teacher_id);
        }

        if (is_numeric($is_featured)){
            $data=$data->whereIsFeatured($is_featured);
        }
        if (is_numeric($classify_id)){
            $ids    = CourseType::whereClassifyId($classify_id)->pluck('course_id')->toArray();
            $data   = $data->whereIn('id',$ids);
        }

        $page_info['total']=$data->count();
        if ($order_by == 'selling'){
            $data=$data->orderBy('sort','asc')
                ->orderByDesc('selling_num')
                ->offset($page * $limit)
                ->limit($limit)
                ->get();
        } else {
            $data=$data->orderBy('sort','asc')
                ->offset($page * $limit)
                ->limit($limit)
                ->get();
        }

        if (count($data) > 0){
            foreach ($data as $item){
//                $item->thumb_url = FileManager::getImgUrl($item->thumb_id);
                $item->thumb_url    = CourseCoverImg::getImgUrlByCourseId($item->id);
                $item->study_type_name = $item->getStudyTypeName($item->study_type);
                $item->teacher_info = Teacher::getTeacherInfo($item->teacher_id);
                $item->label_arr = CourseLabel::getCourseLabel($item->id);
                $item->type_arr = CourseType::getCourseType($item->id);
                $item->try_study = CourseContent::getTryContents($item->id);
                if((int)$item->time_vip_price - $item->time_vip_price == 0) {
                    $item->time_vip_price = (int)$item->time_vip_price;
                }
                if((int)$item->show_price - $item->show_price == 0) {
                    $item->show_price = (int)$item->show_price;
                }
                if((int)$item->price - $item->price == 0){
                    $item->price = (int)$item->price;
                }
                if (in_array($item->id,$buy_ids)){
                    $item->is_buy=1;
                } else {
                    $item->is_buy=0;
                }

                //奖励规则
//                $item->reward_rule = ''
            }
        }
        return response()->json([
            'level'     => 'success',
            'message'   => 'success',
            'data'      => $data,
            'page_info' => $page_info
        ]);
    }

    /**
     * 获取课程详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCourseDetail(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        $userId = $user ? $user->id : 0;

        $id = $request->input('id',0);

        $course = Course::whereId($id)->first();
        if($userId){
            $is_payed_id=Orders::whereUserId($user->id)
                ->whereIsPay(1)
                ->whereIsSuccess(1)
                ->pluck('id')->toArray();
        } else {
            $is_payed_id=[];
        }

        if($course){
//            $course->thumb_url          = CourseCoverImg::getImgUrlByCourseId($course->id);
            $course->thumb_url    = CourseCoverImg::getCourseCoverImgList($course->id,'url');
            if((int)$course->price - $course->price == 0) {
                $course->price = (int)$course->price;
            }
            $course->study_type_name    = $course->getStudyTypeName($course->study_type);
            $course->teacher_info       = Teacher::getTeacherInfo($course->teacher_id);
            $course->type_arr           = CourseType::getCourseType($course->id);
            $course->collection_status  = CourseCollection::getCourseCollectionStatus($id,$userId);
            $course->package_info       = CoursePackageXCourse::getCoursePackages($course->id);
            $course->system_group_info  = SystemGroupXCourse::getCourseGroup($course->id);
            $course->is_buy         = 0;
            if ($userId){
                $isBuy  = OrderItem::whereUserId($userId)->whereIn('order_id',$is_payed_id)->pluck('course_id')->toArray();
                if ($isBuy)
                    $course->is_buy         = 1;
            }


        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $course]);
    }
    public function getPackageDetail(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        $userId = $user ? $user->id : 0;

        $id = $request->input('package_id',0);

        $data = CoursePackage::whereId($id)->whereStatus(1)->first();

        if($data){
            $data->course_list=CoursePackageXCourse::getPackagesCourse($data->id);
        } else {
            return response()->json(['level' => 'error','message' => '套餐已下架','data' => $data]);
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $data]);
    }

    public function getUserGroupDetail(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = $request->input('group_id',0);

        $data = UserGroup::whereId($id)->first();

        if($data){
            $data->owner_info   = UserInfo::getUserInfo($data->user_id);
            $data->is_join      = Orders::whereUserId($user->id)->whereGroupId($id)->first() ? 1 :0;
            $data->join_list    = UserGroupXUser::getJoinUser($data->id);
            $system_group       = SystemGroup::whereId($data->system_groups_id)->first();
            if ($system_group){
                if ($data->status == 2){
                    $system_group->remain_sec = -1;
                } else {
                    $dead_line              = strtotime($data->created_at) + ($system_group->time_limit * 3600);
                    $remain_times           = $dead_line - time();
                    if ($remain_times > 1){
                        $system_group->remain_sec = $remain_times;
                    } else {
                        $system_group->remain_sec = 0;
                    }
                }

            }
            $data->system_group = $system_group;
            $data->course_info  = Course::getCourseInfo($data->course_id);
            $data->price_info   = SystemGroupXCourse::getGroupCoursePrice($data->system_groups_id,$data->course_id);
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $data]);
    }
    public function getMyGroupList(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $status     = $request->input('status');
        $page       = $request->input('page',1);
        $limit      = $request->input('limit',10);
        $page_info  = [
            'page'=>$page,
            'limit'=>$limit,
            'total'=>0
        ];
        $page = $page -1;
        $data = UserGroupXUser::whereUserId($user->id);
        if (is_numeric($status)){
            $data=$data->whereStatus($status);
        }
        $page_info['total']=$data->count();
        $data=$data->orderByDesc('id')->offset($page * $limit)->limit($limit)->get();

        if(count($data) > 0){
            foreach ($data as $item){
                $item->join_list    = UserGroupXUser::getJoinUser($item->user_group_id);
                $user_group         = UserGroup::whereId($item->user_group_id)->first();
                $system_group       = $user_group ? SystemGroup::whereId($user_group->system_groups_id)->first() : null;
                if ($system_group){
//                    $system_group->deadline     = (strtotime($item->created_at) + ($system_group->time_limit * 3600)) ?? 0;
                    if ($item->status == 2){
                        $system_group->remain_sec = -1;
                    } else {
                        $dead_line              = strtotime($item->created_at) + ($system_group->time_limit * 3600);
                        $remain_times           = $dead_line - time();
                        if ($remain_times > 1){
                            $system_group->remain_sec = $remain_times;
                        } else {
                            $system_group->remain_sec = 0;
                        }
                    }

                }
                $item->system_group = $system_group;
                $item->status_name  = UserGroupXUser::getStatusName($item->status);
                $item->course_info  = Course::getCourseInfo($user_group->course_id);
                $item->order_info   = Orders::whereUserId($user->id)->whereGroupId($item->user_group_id)->first();
            }

        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $data,'page_info'=>$page_info]);
    }

    /**
     * 获取课程章节
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCourseContentList(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
//        if(!$user)
//            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $userId = $user ? $user->id : 0;
        $limit    = $request->input('limit',16);
        $page     = $request->input('page',1);
        $courseId = $request->input('course_id',0);

        $pageInfo = [
            'limit'=> $limit,
            'page' =>$page
        ];

        $page -= 1;

        $courseContentList = CourseContent::whereCourseId($courseId);
        if($userId){
            $is_payed_id=Orders::whereUserId($user->id)
                ->whereIsPay(1)
                ->whereIsSuccess(1)
                ->pluck('id')->toArray();
            $buy_ids = OrderItem::whereUserId($user->id)->whereIn('order_id',$is_payed_id)->pluck('course_id')->toArray();
        } else {
            $buy_ids=[];
        }

        $pageInfo['total'] = $courseContentList->count();

        $courseContentList = $courseContentList->orderBy('section_num')
            ->orderByDesc('created_at')
            ->offset($limit * $page)
            ->limit($limit)
            ->get();
        if (count($courseContentList) > 0){
            if (in_array($courseId,$buy_ids)){
                foreach ($courseContentList as $item){
                    $item->video_url = FileManager::getVideoUrl($item->video_id);
                    $item->is_buy=1;
                }
            } else {
                foreach ($courseContentList as $item){
                    if ($item->allow_try)
                        $item->video_url = FileManager::getVideoUrl($item->video_id);
                    else
                        $item->video_url = FileManager::getVideoUrl($item->video_id);
                    $item->is_buy=0;
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $courseContentList,'page_info' => $pageInfo]);
    }

    /**
     * 获取问题
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCourseQuestion(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $limit    = $request->input('limit',16);
        $page     = $request->input('page',1);
        $course_id= $request->input('course_id');

        $pageInfo = [
            'limit'=> $limit,
            'page' => $page
        ];

        $page -= 1;
        $pageInfo['total']   = CourseQuestion::whereCourseId($course_id)->count();
        $data       = CourseQuestion::whereCourseId($course_id)
            ->orderBy('sort')
            ->offset($page * $limit)
            ->limit($limit)
            ->get();
        if (count($data) > 0){
            foreach($data as $item){
                $item->option_info=CourseQuestionOption::whereCourseQuestionId($item->id)
                    ->get(['id','course_question_id','option']);
            }
        }
        return response()->json([
            'level'=>'success',
            'message'=>'success',
            'data'=>$data,
            'page_info'=>$pageInfo
        ]);
    }

    public function answerQuestion(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $question_id    = $request->input('question_id');
        $option_ids     = $request->input('option_id');

        if (!$question_id)
            return response()->json(['level' => 'error','message' => '问题id错误！','data' => '']);

        if (!is_array($option_ids)){
            $option_ids=json_decode($option_ids);
            if (!is_array($option_ids))
                return response()->json(['level' => 'error','message' => '数据格式错误！','data' => $request->all()]);
        }

        $answer_num = CourseQuestionAnswerRecord::whereUserId($user->id)
            ->whereCourseQuestionId($question_id)
            ->count();

        $thisQuestion = CourseQuestion::whereId($question_id)->first();

        if (!$thisQuestion)
            return response()->json(['level' => 'error','message' => '答题发生错误','data' => '']);

        $isBuyedCourse = OrderItem::whereUserId($user->id)
            ->whereCourseId($thisQuestion->course_id)
            ->first();
        if (!$isBuyedCourse){
            return response()->json(['level' => 'error','message' => '你还没有购买该课程','data' => '']);
        }

        if ($thisQuestion->limit_num > 0 && $answer_num >= $thisQuestion->limit_num)
            return response()->json(['level' => 'error','message' => '本题剩余次数已用完，不能再回答了哦','data' => '']);

        $bingo_arr = CourseQuestionOption::whereCourseQuestionId($question_id)
            ->whereIsTrue(1)
            ->pluck('id')
            ->toArray();
        if(!array_diff($option_ids, $bingo_arr) && !array_diff($bingo_arr, $option_ids)){
            //答对了
            CourseQuestionAnswerRecord::addRecord($user->id,$thisQuestion->course_id,$thisQuestion->id,$option_ids,1);
            $result=IntegralDetail::addIntegralByAnswer($user->id,$question_id);
            $message="恭喜你，答对了！获得 $result 积分";
            $is_bingo = 1;
        } else {
            //答错了
            CourseQuestionAnswerRecord::addRecord($user->id,$thisQuestion->course_id,$thisQuestion->id,$option_ids,0);
            $message="答错了哦~";
            $is_bingo = 0;
        }
        return response()->json([
            'level' => 'success',
            'message' => $message,
            'data' => [
                'remain_times'=>$thisQuestion->limit_num ? ($thisQuestion->limit_num - ($answer_num + 1)) : '-',
                'is_bingo'=>$is_bingo
            ]
        ]);

    }

    /**
     * 收藏课程
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function collectionCourse(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $courseId = $request->input('course_id',0);

        $course = Course::whereId($courseId)->whereStatus(1)->first();
        if(!$course)
            return response()->json(['level' => 'error','message' => '课程不存在']);

        $isCollection = CourseCollection::whereCourseId($course->id)->whereUserId($user->id)->first();
        if($isCollection){
            $isCollection->forceDelete();

            return response()->json(['level' => 'success','message' => '取消收藏','data' => $isCollection]);
        }

        $newCourseCollection = new CourseCollection();
        $newCourseCollection->course_id    = $courseId;
        $newCourseCollection->user_id      = $user->id;
        $newCourseCollection->save();

        return response()->json(['level' => 'success','message' => '收藏成功','data' => $newCourseCollection]);
    }

    /**
     * 获取我收藏的课程列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserCollectionCourseList(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $limit    = $request->input('limit',16);
        $page     = $request->input('page',1);

        $pageInfo = [
            'limit'=> $limit,
            'page' =>$page
        ];

        $page -= 1;

        $courseIds = CourseCollection::whereUserId($user->id)->orderByDesc('id')->pluck('course_id')->toArray();

        $courseList = Course::whereStatus(1)->whereIn('id',$courseIds);

        $pageInfo['total'] = $courseList->count();

        $courseList = $courseList->offset($limit * $page)->limit($limit)->get();
        if(count($courseList) > 0){
            foreach ($courseList as $course) {
                $course->thumb_url    = CourseCoverImg::getImgUrlByCourseId($course->id);

                $course->study_type_name = $course->getStudyTypeName($course->study_type);

                $course->teacher_info = Teacher::getTeacherInfo($course->teacher_id);

                $course->label_arr = CourseLabel::getCourseLabel($course->id);

                $course->type_arr = CourseType::getCourseType($course->id);
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $courseList,'page_info' => $pageInfo]);
    }

//    public function courseSharePoster(Request $request){
//        \Log::notice('request->getUri=>'.$request->getUri());
////        return response()->download(base_path().'/public/images/71f0992ce4202a128124e0beb2f7087.png');
////        /** @var User $user */
//        $user = UserManager::isLogin($request);
//        if(!$user)
//            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
//
//        $courseId = $request->input('course_id',0);
//
//        $course = Course::whereId($courseId)->first();
//        if(!$course)
//            return response()->json(['level' => 'error','message' => '课程不存在']);
//
//        $teacher = Teacher::whereId($course->teacher_id)->first();
//        if(!$teacher)
//            return response()->json(['level' => 'error','message' => $teacher]);
//
//        $courseContentOne   = CourseContent::whereCourseId($course->id)->orderBy('section_num')->offset(0)->limit(1)->first();
//        $courseContentTwo   = CourseContent::whereCourseId($course->id)->orderBy('section_num')->offset(1)->limit(1)->first();
//        $courseContentThree = CourseContent::whereCourseId($course->id)->orderBy('section_num')->offset(2)->limit(1)->first();
//
//        //背景图片
//        $backgroundImgInfo = Image::make(url('images/71f0992ce4202a128124e0beb2f7087.png'));
//
//        $courseThumbUrl = CourseCoverImg::getImgUrlByCourseId($course->id);
//          if($courseThumbUrl){
//            $courseThumbInfo = Image::make($courseThumbUrl)->resize(730,733);
//            $backgroundImgInfo->insert($courseThumbInfo,'top-left',0,0);;
//          }
////        if(mb_strlen($course->name) > 10){
////            $courseTitle = mb_substr($course->name,0,10,'utf-8');
////            $backgroundImgInfo->text($courseTitle, 375, 140, function($font) {
////                $font->file(base_path()."/public/front/simsun.ttf");
//////            $font->file(1);
////                $font->size(52);
////                $font->color('#000000');//5a5a5a
////                $font->align('center');
////                $font->valign('top');
////                $font->angle(0);
////            });
////
////            if(mb_strlen($course->name) > 20){
////                $courseTitleTwo = mb_substr($course->name,10,8,'utf-8');
////                $courseTitleTwo .= '...';
////            }else{
////                $courseTitleTwo = mb_substr($course->name,10,10,'utf-8');
////            }
////
////            $backgroundImgInfo->text($courseTitleTwo, 375, 192, function($font) {
////                $font->file(base_path()."/public/front/simsun.ttf");
//////            $font->file(1);
////                $font->size(52);
////                $font->color('#000000');//5a5a5a
////                $font->align('center');
////                $font->valign('top');
////                $font->angle(0);
////            });
////
////        }else{
////            //课程标题
////            $courseTitle = mb_substr($course->name,0,10,'utf-8');
////            //调整商品名称在图片上的位置
////            $backgroundImgInfo->text($courseTitle, 375, 168, function($font) {
////                $font->file(base_path()."/public/front/simsun.ttf");
//////            $font->file(1);
////                $font->size(52);
////                $font->color('#000000');//5a5a5a
////                $font->align('center');
////                $font->valign('top');
////                $font->angle(0);
////            });
////        }
////
////
////        //贱贱的黑色背景
////        $backgroundImgInfo->rectangle(98, 269, 652, 359, function ($draw) {
////            $draw->background('#323334');
////        });
////
////        //简介
////        if(mb_strlen($course->name) > 12){
////            $courseDesc = mb_substr($course->desc,0,10,'utf-8');
////            $courseDesc .= '...';
////        }else{
////            $courseDesc = mb_substr($course->desc,0,12,'utf-8');
////        }
////
////        //调整简介在图片上的位置
////        $backgroundImgInfo->text($courseDesc, 375, 295, function($font) {
////            $font->file(base_path()."/public/front/simsun.ttf");
//////            $font->file(1);
////            $font->size(40);
////            $font->color('#F9C332');//5a5a5a
////            $font->align('center');
////            $font->valign('top');
////            $font->angle(0);
////        });
////
////        //课程类型
////        $jiantouLeft = Image::make(url('images/jiantou.png'));
////
////        $backgroundImgInfo->insert($jiantouLeft,'top-left',121,418);
////
////        $courseType = CourseType::whereCourseId($course->id)->first();
////        if($courseType){
////            $classifyName = Classify::getClassifyName($courseType->classify_id);
////            $backgroundImgInfo->text('课程类型：' . $classifyName, 375, 410, function($font) {
////                $font->file(base_path()."/public/front/simsun.ttf");
//////            $font->file(1);
////                $font->size(36);
////                $font->color('#333333');//5a5a5a
////                $font->align('center');
////                $font->valign('top');
////                $font->angle(0);
////            });
////        }
////
////        $jiantouRight = Image::make(url('images/jiantou2.png'));
////
////        $backgroundImgInfo->insert($jiantouRight,'top-right',121,418);
////
////        if($teacher->photo_id != 0){
////            /** @var Images $thisImage */
////            $thisImage = Images::whereId($teacher->photo_id)->first();
////            if($thisImage){
////                /** @var Files $thisFile */
////                $thisFile = Files::whereId($thisImage->file_id)->first();
////                if($thisFile){
////                    $teacherPhotoImgContent = $thisFile->getContent();
////                }else{
////                    $teacherPhotoImgContent = url('images/photo.png');
////                }
////            }else{
////                $teacherPhotoImgContent = url('images/photo.png');
////            }
////        }else{
////            $teacherPhotoImgContent = url('images/photo.png');
////        }
////
////        //教师头像
////        $teacherPhotoImgInfo = Image::make($teacherPhotoImgContent)->resize(212,212);
////
////        //调整教师头像在图片上的位置
////        $backgroundImgInfo->insert($teacherPhotoImgInfo,'top-left',269,540);
////
////        //第一章节
////        if($courseContentOne && $courseContentOne->section_name){
////            //对钩
////            $duihaoImgInfo = Image::make(url('images/gou2.png'));
////
////            $backgroundImgInfo->insert($duihaoImgInfo,'top-left',138,795);
////
////            $courseContentOneName = mb_substr($courseContentOne->section_name,0,16,'utf-8');
////
////            $backgroundImgInfo->text($courseContentOneName, 172, 790, function($font) {
////                $font->file(base_path()."/public/front/simsun.ttf");
//////            $font->file(1);
////                $font->size(26);
////                $font->color('#333333');//5a5a5a
////                $font->align('left');
////                $font->valign('top');
////                $font->angle(0);
////            });
////        }
////
////        //第二章节
////        if($courseContentTwo && $courseContentTwo->section_name){
////            //对钩
////            $duihaoImgInfo = Image::make(url('images/gou2.png'));
////
////            $backgroundImgInfo->insert($duihaoImgInfo,'top-left',138,850);
////
////            $courseContentTwoName = mb_substr($courseContentTwo->section_name,0,16,'utf-8');
////
////            $backgroundImgInfo->text($courseContentTwoName, 172, 844, function($font) {
////                $font->file(base_path()."/public/front/simsun.ttf");
//////            $font->file(1);
////                $font->size(26);
////                $font->color('#333333');//5a5a5a
////                $font->align('left');
////                $font->valign('top');
////                $font->angle(0);
////            });
////        }
////
////        //第三章节
////        if($courseContentThree && $courseContentThree->section_name){
////            //对钩
////            $duihaoImgInfo = Image::make(url('images/gou2.png'));
////
////            $backgroundImgInfo->insert($duihaoImgInfo,'top-left',138,905);
////
////            $courseContentThreeName = mb_substr($courseContentThree->section_name,0,16,'utf-8');
////
////            $backgroundImgInfo->text($courseContentThreeName, 172, 898, function($font) {
////                $font->file(base_path()."/public/front/simsun.ttf");
//////            $font->file(1);
////                $font->size(26);
////                $font->color('#333333');//5a5a5a
////                $font->align('left');
////                $font->valign('top');
////                $font->angle(0);
////            });
////        }
//
//        //一起学习背景
//        $footerTitleImgInfo = Image::make(url('images/heikuangkuang.png'));
//        $backgroundImgInfo->insert($footerTitleImgInfo,'top-left',45,743);
//
//        //一起学习
//        $titleContent = '一起学习';
//        $backgroundImgInfo->text($titleContent, 67, 754, function($font) {
//            $font->file(base_path()."/public/front/simsun.ttf");
////            $font->file(1);
//            $font->size(24);
//            $font->color('#F7F7F7');//5a5a5a
//            $font->align('left');
//            $font->valign('top');
//            $font->angle(0);
//        });
//
//        //转发海报分享给好友
//        $footerContent = '转发海报分享给好友';
//        $backgroundImgInfo->text($footerContent, 45, 811, function($font) {
//            $font->file(base_path()."/public/front/simsun.ttf");
////            $font->file(1);
//            $font->size(24);
//            $font->color('#333333');//5a5a5a
//            $font->align('left');
//            $font->valign('top');
//            $font->angle(0);
//        });
//
//        //分割线
//        $footerLineImgInfo = Image::make(url('images/zhixian.png'));
//        $backgroundImgInfo->insert($footerLineImgInfo,'top-left',45,847);
//
//        //分享人信息
//        $userNickname = $user->userInfo ? $user->userInfo->nickname : '';
//        $nickname = $userNickname . "邀请你一起学习";
//        if(mb_strlen($nickname) > 15){
//            $shareUserPhotoUrl = Image::make(url('images/course_share_background.png'))->resize(36,36);
//            // 这是画布和背景
//            $new= Image::canvas(36,36, '#ffffff');
//            // 把头像处理成圆形
//            $r = $shareUserPhotoUrl->width() / 2;
//            for ($x = 0; $x < $shareUserPhotoUrl->width(); $x++) {
//                for ($y = 0; $y < $shareUserPhotoUrl->height(); $y++) {
//                    $c = $shareUserPhotoUrl->pickColor($x, $y, 'array');
//                    if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) {
//                        $new->pixel($c, $x, $y);
//                    }
//                }
//            }
//            $backgroundImgInfo->insert($new,'top-left',45,880);
//
//            $nicknameOne = mb_substr($nickname,0,15,'utf-8');
//            $backgroundImgInfo->text($nicknameOne, 107, 887, function($font) {
//                $font->file(base_path() . "/public/front/simsun.ttf");
////            $font->file(1);
//                $font->size(24);
//                $font->color('#333333');//5a5a5a
//                $font->align('left');
//                $font->valign('top');
//                $font->angle(0);
//            });
//
//            $nicknameTwo = mb_substr($nickname,15,15,'utf-8');
//            $backgroundImgInfo->text($nicknameTwo, 107, 920, function($font) {
//                $font->file(base_path() . "/public/front/simsun.ttf");
////            $font->file(1);
//                $font->size(24);
//                $font->color('#333333');//5a5a5a
//                $font->align('left');
//                $font->valign('top');
//                $font->angle(0);
//            });
//        }else{
//            $shareUserPhotoUrl = Image::make(url('images/course_share_background.png'))->resize(36,36);
//            // 这是画布和背景
//            $new= Image::canvas(36,36, '#ffffff');
//            // 把头像处理成圆形
//            $r = $shareUserPhotoUrl->width() / 2;
//            for ($x = 0; $x < $shareUserPhotoUrl->width(); $x++) {
//                for ($y = 0; $y < $shareUserPhotoUrl->height(); $y++) {
//                    $c = $shareUserPhotoUrl->pickColor($x, $y, 'array');
//                    if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) {
//                        $new->pixel($c, $x, $y);
//                    }
//                }
//            }
//            $backgroundImgInfo->insert($new,'top-left',45,880);
//
//            $backgroundImgInfo->text($nickname, 107, 887, function($font) {
//                $font->file(base_path() . "/public/front/simsun.ttf");
////            $font->file(1);
//                $font->size(24);
//                $font->color('#333333');//5a5a5a
//                $font->align('left');
//                $font->valign('top');
//                $font->angle(0);
//            });
//        }
//
//
//        //底部内容
//        $footerContentOne = '长按识别二维码';
//
//        $backgroundImgInfo->text($footerContentOne, 538, 892, function($font) {
//            $font->file(base_path() . "/public/front/simsun.ttf");
////            $font->file(1);
//            $font->size(20);
//            $font->color('#9F9F9F');//5a5a5a
//            $font->align('left');
//            $font->valign('top');
//            $font->angle(0);
//
//        });
//
//        $scene = "invite_user_id=$user->id&id=$course->id";
//        $path  = 'pages/course/courseDetail/courseDetail?' . $scene;      //梓杰给
//
//        //生成微信小程序的二维码图片
//        $wxAppQrCodeContent = WechatLogin::getWxaCodeBYToken($path);
//        if($wxAppQrCodeContent){
//            //获取二维码图片
//            $wxAppQrCodeImgINfo = Image::make($wxAppQrCodeContent)->resize(100,100);
//            //调整二维码图片在图片上的位置
//            $backgroundImgInfo->insert($wxAppQrCodeImgINfo,'top-left',561,770);
//        }else{
//            return response()->json(['level' => 'error','message' => '二维码生成失败,请联系客服']);
//        }
//
////        //获取二维码图片
////        $wxAppQrCodeImgINfo = Image::make(url('images/renxieqrcode.jpg'))->resize(100,100);
////        //调整二维码图片在图片上的位置
////        $backgroundImgInfo->insert($wxAppQrCodeImgINfo,'top-left',561,770);
//
//        //输出图片
////        $response = response()->make($backgroundImgInfo->encode('jpg'));
////        $response->header('Content-Type', 'image/jpeg');
////        return $response;
//
//        $backgroundImgInfo->encode('jpg');
//        //输出图片
//        $qrcodeFile = FileManager::saveFileByFileContent($backgroundImgInfo->encoded, 'course_share_img.jpg');
//        $imageModel = new Images();
//        $imageModel->files()->associate($qrcodeFile);
//        $imageModel->img_type = $qrcodeFile->file_type;
//        $imageModel->img_name = $qrcodeFile->file_name;
//        $imageModel->save();
//
//        $imgUrl = FileManager::getImgUrl($imageModel->id);
//
//        return $imgUrl;
//    }

    public function courseSharePoster(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $courseId = $request->input('course_id',0);

        $course = Course::whereId($courseId)->first();
        if(!$course)
            return response()->json(['level' => 'error','message' => '课程不存在']);

        $teacher = Teacher::whereId($course->teacher_id)->first();
        if(!$teacher)
            return response()->json(['level' => 'error','message' => $teacher]);

        //背景图片
        $backgroundImgInfo = Image::make(url('images/71f0992ce4202a128124e0beb2f7087.png'));

        $courseThumbUrl = CourseCoverImg::getImgUrlByCourseId($course->id);
        if($courseThumbUrl){
            $courseThumbInfo = Image::make($courseThumbUrl)->resize(730,733);
            $backgroundImgInfo->insert($courseThumbInfo,'top-left',0,0);;
        }

        //使用说明
        $titleContent = '使用说明';
        $backgroundImgInfo->text($titleContent, 50, 770, function($font) {
            $font->file(base_path()."/public/front/simsun.ttf");
//            $font->file(1);
            $font->size(32);
            $font->color('#000000');//5a5a5a
            $font->align('left');
            $font->valign('top');
            $font->angle(0);
        });

        //分割线
        $footerLineImgInfo = Image::make(url('images/zhixian.png'));
        $backgroundImgInfo->insert($footerLineImgInfo,'top-left',50,820);

        //分享信息
        $infoOne = "请长按识别二维码，进入律法管家";
        $infoTwo = "小程序，根据页面提示进行购买。";
        $infoThree = "即可拥有自己的私人法律顾问。";

        $backgroundImgInfo->text($infoOne, 50, 850, function($font) {
            $font->file(base_path() . "/public/front/simsun.ttf");
//            $font->file(1);
            $font->size(24);
            $font->color('#888888');//5a5a5a
            $font->align('left');
            $font->valign('top');
            $font->angle(0);
        });

        $backgroundImgInfo->text($infoTwo, 50, 880, function($font) {
            $font->file(base_path() . "/public/front/simsun.ttf");
//            $font->file(1);
            $font->size(24);
            $font->color('#888888');//5a5a5a
            $font->align('left');
            $font->valign('top');
            $font->angle(0);
        });

        $backgroundImgInfo->text($infoThree, 50, 910, function($font) {
            $font->file(base_path() . "/public/front/simsun.ttf");
//            $font->file(1);
            $font->size(24);
            $font->color('#888888');//5a5a5a
            $font->align('left');
            $font->valign('top');
            $font->angle(0);
        });

        $scene = "invite_user_id=$user->id&id=$course->id";
        $path  = 'pages/course/courseDetail/courseDetail?' . $scene;      //梓杰给

        //生成微信小程序的二维码图片
        $wxAppQrCodeContent = WechatLogin::getWxaCodeBYToken($path);
        if($wxAppQrCodeContent){
            //获取二维码图片
            $wxAppQrCodeImgINfo = Image::make($wxAppQrCodeContent)->resize(120,120);
            //调整二维码图片在图片上的位置
            $backgroundImgInfo->insert($wxAppQrCodeImgINfo,'top-left',561,810);
        }else{
            return response()->json(['level' => 'error','message' => '二维码生成失败,请联系客服']);
        }

//        //输出图片
//        $response = response()->make($backgroundImgInfo->encode('jpg'));
//        $response->header('Content-Type', 'image/jpeg');
//        return $response;

        $backgroundImgInfo->encode('jpg');
        //输出图片
        $qrcodeFile = FileManager::saveFileByFileContent($backgroundImgInfo->encoded, 'course_share_img.jpg');
        $imageModel = new Images();
        $imageModel->files()->associate($qrcodeFile);
        $imageModel->img_type = $qrcodeFile->file_type;
        $imageModel->img_name = $qrcodeFile->file_name;
        $imageModel->save();

        $imgUrl = FileManager::getImgUrl($imageModel->id);

        return $imgUrl;
    }

    public function getSignQRCodeUrl(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $courseId = $request->input('course_id',0);
        if (!$courseId){
            return response()->json(['level' => 'error','message' => '参数错误！','data' => '']);
        }
        $is_payed_id    = Orders::whereUserId($user->id)
            ->whereIsPay(1)
            ->whereIsSuccess(1)
            ->pluck('id')->toArray();
        /** @var OrderItem $is_buy */
        $is_buy         = OrderItem::whereUserId($user->id)
            ->whereIn('order_id',$is_payed_id)
            ->whereCourseId($courseId)
            ->first();
        if (!$is_buy){
            return response()->json(['level' => 'error','message' => '还没购买该课程','data' => '']);
        }
        if ($is_buy->sign_img_id){
            $url=FileManager::getImgUrl($is_buy->sign_img_id);
            return response()->json(['level' => 'success','message' => '获取成功','data' => $url]);
        }
//        $data   = explode('#',$is_buy->item_num,2);
        $rand   = rand(10000,99999);
        $str    = dechex($is_buy->id * $rand).$rand;
        $QR     = new QrCode($str);
        $QR     = $QR->setSize(480)
            ->setErrorCorrection('high')
            ->setImageType(QrCode::IMAGE_TYPE_JPEG)
            ->render()
            ->get();
        $file   = FileManager::saveFileByFileContent($QR,"signCode$is_buy->item_num.jpg");
        if ($file){
            $imageModel = Images::whereFileId($file->id)->first();
            if(!$imageModel){
                $imageModel = new Images();
                $imageModel->file_id = $file->id;
                $imageModel->img_name= "signCode$is_buy->item_num.jpg";
                $imageModel->img_type= $file->file_type;
                $imageModel->save();
            }
            $is_buy->sign_img_id =$imageModel->id;
            $is_buy->save();
        } else {
            return response()->json(['level' => 'error','message' => '图片保存失败','data' => '']);
        }
        $url=FileManager::getImgUrl($is_buy->sign_img_id);
        return response()->json(['level' => 'success','message' => '获取成功','data' => $url]);
    }

    public function courseSign(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $payload = $request->input('payload');
        if (!$payload)
            return response()->json(['level' => 'error','message' => '参数错误！']);

        try{
            $end    = substr($payload,-5);
            $prefix = substr($payload,0,-5);
            $prefixDec = hexdec($prefix);
            $start  = $prefixDec / $end;
            \Log::notice("payload=>$payload,end=>$end,prefix=>$prefix,prefixDec=>$prefixDec,start=>$start");
            if ($prefixDec % $end != 0)
                return response()->json(['level' => 'error','message' => '签到错误']);
            $orderItem = OrderItem::whereId($start)->first();
            if (!$orderItem){
                return response()->json(['level'=>'error','message'=>'没有该课程的购买信息','data'=>[]]);
            }
            $order=Orders::whereId($orderItem->order_id)->first();
            if (!$order)
                return response()->json(['level'=>'error','message'=>'没有该课程的订单信息','data'=>[]]);
            if($order->is_pay == 0)
                return response()->json(['level'=>'error','message'=>'该课程的订单还没有支付','data'=>[]]);
            if($order->is_success == 0)
                return response()->json(['level'=>'error','message'=>'该课程购买不成功','data'=>[]]);
            $courseSign = CourseSignRecord::whereUserId($orderItem->user_id)
                ->orderByDesc('id')
                ->first();
            if ($courseSign){
                if ((strtotime($courseSign->created_at) + 90) >= time()){
                    if ($courseSign->course_id == $orderItem->course_id){
                        return response()->json(['level'=>'error','message'=>'90秒内不能重复签到','data'=>[]]);
                    } else {
                        $courseSign->course_id = $orderItem->course_id;
                        $courseSign->save();
                        return response()->json(['level'=>'success','message'=>'签到修改成功',
                            'data'=>
                                [
                                    'user_info'=>UserInfo::getUserInfo($orderItem->user_id),
                                    'course_info'=>Course::getCourseInfo($orderItem->course_id)
                                ]
                        ]);
                    }
                }
            }


            $record = new CourseSignRecord();
            $record->user_id    =$orderItem->user_id;
            $record->course_id  =$orderItem->course_id;
            $record->save();
            $message=IntegralDetail::addIntegralBySign($record->user_id,$record->course_id);
        } catch (\Exception $exception){
            return response()->json(['level'=>'error','message'=>$exception->getMessage(),'data'=>[]]);
        }
        return response()->json(['level'=>'success','message'=>'签到成功',
            'data'=>
                [
                    'user_info'=>UserInfo::getUserInfo($orderItem->user_id),
                    'course_info'=>Course::getCourseInfo($orderItem->course_id),
                    'integral_message'=>$message
                ]
        ]);

    }

    /**
     * 记录学习时长
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function recordCourseStudyLength(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $courseId = $request->input('course_id',0);
        $timeLength = $request->input('time_length',0);

        $thisCourse=Course::whereId($courseId)->whereStatus(1)->first();
        if(!$thisCourse)
            return response()->json(['level' => 'error','message' => '课程不存在']);

        $courseStudyLength = CourseStudyLenght::whereCourseId($thisCourse->id)->whereUserId($user->id)->first();
        if(!$courseStudyLength)
            $courseStudyLength = new CourseStudyLenght();

        $courseStudyLength->user_id          = $user->id;
        $courseStudyLength->course_id        = $thisCourse->id;
        $courseStudyLength->cumulative_time += $timeLength;
        $courseStudyLength->save();

        return response()->json(['level' => 'success','message' => '记录成功','data' => $courseStudyLength]);
    }

    /**
     * 生成服务的分享二维码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\WechatException
     */
    public function generateSharePoster(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $courseId = $request->input('course_id') ?? 0;

        $course = Course::whereId($courseId)->whereStatus(1)->first();
        if(!$course)
            return response()->json(['level' => 'error','message' => '服务不存在']);

        $thisUserCoursePoster = UserCoursePoster::whereUserId($user->id)->whereCourseId($course->id)->first();
        if($thisUserCoursePoster && $thisUserCoursePoster->img_id && $course->poster_img_id == $thisUserCoursePoster->poster_img_id){
            $imgUrl = FileManager::getImgUrl($thisUserCoursePoster->img_id);
        }else{
            if($course->poster_img_id){
                $posterImgUrl = FileManager::getImgUrl($course->poster_img_id);
            }else{
                if($course->id == 34)
                    $posterImgUrl = url('images/backage_img.png');
                else{
                    $posterImgUrl = url('images/backage_img2.jpg');
                }
            }

            $backageImgInfo = Image::make($posterImgUrl);

            $scene = "invite_user_id=$user->id&id=$course->id";
            $path  = 'pages/course/courseDetail/courseDetail?' . $scene;

            //生成微信小程序的二维码图片
            $wxAppQrCodeContent = WechatLogin::getWxaCodeBYToken($path);
            if($wxAppQrCodeContent) {
                //获取二维码图片
                $wxAppQrCodeImgINfo = Image::make($wxAppQrCodeContent)->resize(150, 150);

                $backageImgInfo->insert($wxAppQrCodeImgINfo,'top-left',450,1060);
                $backageImgInfo->encode('jpg');

                $qrcodeFile = FileManager::saveFileByFileContent($backageImgInfo->encoded, 'share_img.jpg', $backageImgInfo->mime());
                $imageModel = new Images();
                $imageModel->files()->associate($qrcodeFile);
                $imageModel->img_type = $qrcodeFile->file_type;
                $imageModel->img_name = $qrcodeFile->file_name;
                $imageModel->save();

                $userCoursePoster = UserCoursePoster::whereUserId($user->id)->whereCourseId($course->id)->first();
                if(!$userCoursePoster)
                    $userCoursePoster = new UserCoursePoster();

                $userCoursePoster->user_id = $user->id;
                $userCoursePoster->course_id = $course->id;
                $userCoursePoster->poster_img_id = $course->poster_img_id;
                $userCoursePoster->img_id = $imageModel->id;
                $userCoursePoster->save();

                $imgUrl = FileManager::getImgUrl($imageModel->id);
            }else{
                return response()->json(['level' => 'error','message' => '二维码生成失败']);
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $imgUrl]);
    }

    /**
     * 代理人申请
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function agentApply(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $realname                = $request->input('realname') ?? '';
        $idCard                  = $request->input('id_card') ?? '';
        $phone                   = $request->input('phone') ?? '';
        $type                    = $request->input('type') ?? 'personal';
        $companyName             = $request->input('company_name') ?? '';
        $unifiedSocialCreditCode = $request->input('unified_social_credit_code') ?? '';
        $contactsPeople          = $request->input('contacts_people') ?? '';

        $isReview = AgentApply::whereUserId($user->id)->whereReview(0)->first();
        if($isReview)
            return response()->json(['level' => 'error','message' => '您的申请正在处理中，请勿重复提交！']);

        $isSuccess = AgentList::whereUserId($user->id)->first();
        if($isSuccess)
            return response()->json(['level' => 'error','message' => '您已经是推广代理人了！']);

        if($type == 'personal'){
            if(empty($realname))
                return response()->json(['level' => 'error','message' => '请填写真实姓名']);

            if(empty($idCard))
                return response()->json(['level' => 'error','message' => '请填写身份证号']);

            if(empty($phone))
                return response()->json(['level' => 'error','message' => '请填写手机号']);
        }elseif($type == 'enterprise'){
            if(empty($companyName))
                return response()->json(['level' => 'error','message' => '请填写公司名称']);

            if(empty($unifiedSocialCreditCode))
                return response()->json(['level' => 'error','message' => '请填写统一社会信用代码']);

            if(empty($contactsPeople))
                return response()->json(['level' => 'error','message' => '请填写联系人']);

            if(empty($phone))
                return response()->json(['level' => 'error','message' => '请填写手机号']);
        }else{
            return response()->json(['level' => 'error','message' => '参数错误']);
        }

        $newAgentApply = new AgentApply();
        $newAgentApply->user_id                      = $user->id;
        $newAgentApply->realname                     = $realname;
        $newAgentApply->id_card                      = $idCard;
        $newAgentApply->type                         = $type;
        $newAgentApply->company_name                 = $companyName;
        $newAgentApply->unified_social_credit_code   = $unifiedSocialCreditCode;
        $newAgentApply->contacts_people              = $contactsPeople;
        $newAgentApply->phone                        = $phone;
        $newAgentApply->save();

        return response()->json(['level' => 'success','message' => '申请提交成功','data' => $newAgentApply]);
    }

}
